// pages/shopping_Cart/shopping_Cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    resource: [],
    disable: [],
    allPrice: "",
    isCheckAll: false,
    choosedList: [],
    isCheckedList: [],
    choosedLength: 0,
    deleteTag: [],
    opration:"编辑",
    // 是否显示删除
    delete:false,
    // 是否显示总价
    totalstate:false,
    // 购物车空
    empty:false,
  },
  // 去添加
  goadd:function () {
    wx.switchTab({
      url: '/pages/shopping/shopping',
    })
  },
  // 编辑
  opration(){
    
if (this.data.opration=="编辑") {
  // 缓存之前状态
  console.log(this.data.isCheckAll)
  let orign={
    'check':this.data.choosedList,
    'checkall':this.data.isCheckAll,
    'choosedLength':this.data.choosedLength
  }
  wx.setStorageSync('orign',orign)
    // 初始化
  this.setData({
    opration:"完成",
    delete:true,
    choosedList: [],
    isCheckAll: false,
    choosedLength:0,
    totalstate:false,
  })
}else{
  // 恢复状态
  this.setData({
    opration:"编辑",
    delete:false,
    choosedList:wx.getStorageSync('orign').check,
    isCheckAll:wx.getStorageSync('orign').checkall,
    choosedLength:wx.getStorageSync('orign').choosedLength,
  })
  this.computedAllPrice()
}
  },
// 全选删除
deleteall(){
  let that=this
  var len=this.data.choosedList.length
  let good=this.data.resource;
     for (let i = 0; i <this.data.choosedList.length; i++) {
     // 请求删除接口
     let idx=parseInt(that.data.choosedList[i])
     new Promise((resolve, reject) => {
      wx.request({
        url: 'http://api_dev.wanxikeji.cn/api/shoppingCarDelete',
        method: "POST",
        data: {
          token: this.data.token,
          shopping_car_id:this.data.resource[this.data.choosedList[i]].shopping_car_id 
        },
        success: (res) => resolve(res.data)
      }) 
    }).then(res=>{
      that.data.configInfo.splice(idx,1)
      that.setData({
        configInfo:that.data.configInfo
      })
      console.log(that.data.configInfo)
      if(i==len-1){
        if(res.code == 2000){
          that.setData({
            choosedLength:0
          })
          that.computedAllPrice()
         
        }
      }
    }) 
     // 显示其他
     good=good.filter(item=>{
      if (item!==this.data.resource[this.data.choosedList[i]]) {
        console.log(item);
        return item
      }
    })
 
     }
  
  this.setData({
    resource:good,
    choosedList:[]
  })
  
  // 计算总价
  // this.computedAllPrice()
},
  // 增加数量
  countAdd(e) {
    let {
      index
    } = e.currentTarget.dataset
    this.data.resource[index].num++
    let count = this.data.resource[index].num
    this.setData({
      resource: this.data.resource
    })
    this.changeMoney(index, count)
  },

  // 减少数量
  countSub(e) {
    let {
      index
    } = e.currentTarget.dataset
    let count = this.data.resource[index].num
    count = count > 1 ? count - 1 : count
    let disable = count == 1 ? true : false
    this.data.resource[index].num = count
    this.setData({
      resource: this.data.resource
    })
    this.changeMoney(index, count)
  },

  // 输入数量
  changeCount(e) {
    let count = e.detail.value
    let {
      index
    } = e.currentTarget.dataset
    // 判断count数量
    count = Number.isNaN(Number(count)) ? "" : count === "" ? count : count < 1 ? 1 : count
    // 判断减号是否能点击
    let disable = count == 1 ? true : false
    this.data.disable[index] = disable
    // 设置数据数量
    this.data.resource[index].num = count
    this.setData({
      resource: this.data.resource,
      disable: this.data.disable
    })
    // 调用函数修改价格
    this.changeMoney(index, count)
  },
  // 改变价格
  changeMoney(index, count) {
    console.log(index)
    let price = this.data.resource[index].price
    this.data.resource[index].money = (price * count).toString()
    this.setData({
      resource: this.data.resource
    })
    this.computedAllPrice()
  },
  // 全选
  checkAll(e) {
    let dataLength = this.data.resource.length
    let chooseLength = this.data.choosedList.length
    if (dataLength === chooseLength) {
      this.setData({
        choosedList: []
      })
    } else {

      this.setData({
        choosedList: [...Array(dataLength)].map((item, index) => item = index.toString()),
        isCheckAll:!this.data.isCheckAll
      })
    }
    this.setData({
      choosedLength: this.data.choosedList.length
    })
    this.computedAllPrice()
  },
  // 单选
  choosing(e) {
    let choosedList = e.detail.value
    if (choosedList.length === this.data.resource.length) {
      this.setData({
        isCheckAll: true
      })
    } else {
      this.setData({
        isCheckAll: false
      })
    }
    this.setData({
      choosedList,
    })
    this.setData({
      choosedLength: this.data.choosedList.length
    })
    this.computedAllPrice()
    console.log(this.data.choosedList)
  },
  // 关闭删除购物车
  cancleDelete() {
    console.log(111111)
    let deleteTag = this.data.deleteTag.map(item => item = false)
    this.setData({
      deleteTag
    })
  },
  // 打开删除购物车
  openDeleteItem(e) {
    let {
      index
    } = e.currentTarget.dataset
    this.data.deleteTag[index] = true
    this.setData({
      deleteTag: this.data.deleteTag
    })
  },
  // 删除购物车
  deleteItem(e) {
    let {
      index
    } = e.currentTarget.dataset
    let shoppingCarId = this.data.resource[index].shopping_car_id
    let self = this

    new Promise((resolve, reject) => {
      wx.request({
        url: 'http://api_dev.wanxikeji.cn/api/shoppingCarDelete',
        method: "POST",
        data: {
          token: this.data.token,
          shopping_car_id: shoppingCarId
        },
        success: (res) => resolve(res.data)
      })
    }).then(
      res => {
        if (res.code == 2000) {
          self.data.resource.splice(index, 1)
          self.data.deleteTag.splice(index, 1)
          self.setData({
            resource: self.data.resource,
            deleteTag: self.data.deleteTag,
          })
          
          this.computedAllPrice()
         
          console.log("删除成功")
        }
      },
      err => {

      }
    )
  },
  // 计算总价
  computedAllPrice() {
    let choosedList = this.data.choosedList
    // 获取价格
    // 购物车为空 显示购物车为空界面
    if (this.data.resource=="") {
      this.setData({
        totalstate:false,
        empty:true
      }) 
    }else{
       let allPrice = choosedList.reduce((prev, item) => {
      prev = Number(this.data.resource[item].money) + prev
      return prev
    }, 0).toString()
    this.setData({
      totalstate:true,
      allPrice
    })
    }  
  },
  // 去支付
  goPay() {
    if (this.data.choosedLength==0) {
      console.log(1);
      return
    }
    
    let {
      choosedList,
      allPrice
    } = this.data
    console.log(this.data)
    let data = {}
    let shoppingCarIds = choosedList.reduce((prev, item) => {
      let shoppingCarId = this.data.resource[item].shopping_car_id
      prev.push(shoppingCarId)
      data[shoppingCarId] = this.data.resource[item]
      return prev
    }, [])
    console.log(allPrice)
    console.log(shoppingCarIds)
    console.log(data)
    wx.navigateTo({
      url: '../order_Confirm/order_Confirm',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('transfer', {
          data: {
            allPrice,
            shoppingCarIds,
            data
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let self = this
    let getToken = new Promise((reslove, reject) => {
      wx.getStorage({
        key: 'token',
        success(res) {
          self.setData({token:res.data})
          reslove(res.data)
        }
      })
    }).then(
      res => {
        // 获取购物车列表
        new Promise((resolve, reject) => {
          wx.request({
            url: 'http://api_dev.wanxikeji.cn/api/shoppingCarList',
            data: {
              token: res
            },
            success(res) {
              resolve(res)
             if (res.data.data.data=="") {
              self.setData({empty:true}) 
             }
            }
          })
        }).then(
          res => {
            let chooseInfo = []
            let deleteTag = []
            console.log(res)
            // 获取配置信息
            let configInfo = res.data.data.data.reduce((pre, item) => {
              chooseInfo.push(false)
              deleteTag.push(false)
              let tmp = {}
              let skuInfo = JSON.parse(item.sku)[0].optional
              Object.keys(skuInfo).forEach(key => {
                tmp[key]= skuInfo[key]
              })
              pre.push(tmp)
              return pre
            }, [])
            console.log(configInfo)
            configInfo=configInfo.reverse()
            self.setData({
              resource: JSON.parse(JSON.stringify(res.data.data.data)).reverse(),
              configInfo,
              chooseInfo,
              deleteTag
            })

            console.log(self.data.resource,configInfo)
            if(options.def){
              console.log(this.data.resource)
             self.setData({
               choosedList: ["0"]
             })
             self.computedAllPrice()
             self.setData({
               choosedLength: this.data.choosedList.length,
               
             })
           }
          },
          err => {
            console.log(res)

          }
        )
      }
    )
     
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})